﻿using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Xml.Linq;

namespace VisualRibbonEditor
{
	public partial class UnHideDialog : UserControl, IDialog
	{

		public UnHideDialog()
		{
			InitializeComponent();

			LoadHiddenControls();
		}

		private void LoadHiddenControls()
		{
			itemList.Items.Clear();
			foreach (XElement el in MainWindow.CurrentSolution.RibbonDiffXml.Descendants("HideCustomAction"))
			{
				ListBoxItem i = new ListBoxItem();
				i.Content = el.AttributeValue("Location");
				itemList.Items.Add(i);
			}
		}

		private void OKButton_Click(object sender, RoutedEventArgs e)
		{
			if (itemList.SelectedItems.Count == 0)
			{
				MessageBox.Show("You must select an item");
				return;
			}

			RemoveSelectedItems();
 
			if (DialogClosed != null)
			{
				DialogClosed(true); 
			}
		}


		private void RemoveSelectedItems()
		{
			List<string> locations = new List<string>();
			foreach( ListBoxItem li in itemList.SelectedItems)
			{
				locations.Add(li.Content.ToString());
			}

			List<XElement> elementsToRemove = new List<System.Xml.Linq.XElement>();
			foreach (XElement el in MainWindow.CurrentSolution.RibbonDiffXml.Descendants("HideCustomAction"))
			{
				if (locations.Contains(el.AttributeValue("Location")))
				{
					elementsToRemove.Add(el);
				}
			}

			foreach (XElement el in elementsToRemove)
			{
				el.Remove();
			}
		}

		/// <summary>
		/// user clicked the cancel button. Call DialogClose event with NULL to indicate a cancel.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void CancelButton_Click(object sender, RoutedEventArgs e)
		{
			if (DialogClosed != null)
			{
				DialogClosed(null);
			}
		}

		public event CloseDialogHandler DialogClosed;

		public bool CurrentSolutionHasHiddenItems()
		{
			XElement el = MainWindow.CurrentSolution.RibbonDiffXml.Descendants("HideCustomAction").FirstOrDefault();
			return el != null;
		}

		private void UnHideDialog_KeyUp(object sender, KeyEventArgs e)
		{
			switch (e.Key) //
			{
				// ENTER
				case Key.Enter:
					OKButton_Click(sender, new RoutedEventArgs());
					break;
				// ESC
				case Key.Escape:
					if (DialogClosed != null) DialogClosed(null);
					break;
				default:
					break;
			}
		}

	}

}
